<?php

namespace App\DesignPatterns\Strategy;

use App\Models\User;
use App\Models\Recharge;

/**
 * 法币交易订单状态修改
 */
class RechOrderCollection
{
    private $status; //订单状态

    private  $uid; //用户id

    private  $rid; //交易单id

    private  $handle; //处理流程

    public function __construct(int $status, int $uid, int $rid)
    {
        $this->status = $status;

        $this->uid = $uid;

        $this->rid = $rid;
    }
    /**
     * 执行
     */
    public function entry()
    {
        $status = $this->checkStatus();
        if ($status === true) {
            //return response()->json(['status' => 0, 'msg' => '订单状态值错误']);
            return respF(3003);
        }

        $uid = $this->checkUid();
        if ($uid === true) {
            //return response()->json(['status' => 0, 'msg' => '用户不存在']);
            return respF(1001);
        }

        $rid = $this->checkRid();
        if ($rid === true) {
            //return response()->json(['status' => 0, 'msg' => '订单不存在']);
            return respF(1002);
        }

        if ($this->status == 2) {
            $this->setHandle(new PayHandle());
        }

        if ($this->status == 3) {
            $this->setHandle(new DoneHandle());
        }
        
        if ($this->status == 4) {
            $this->setHandle(new CancelHandle());
        }

        return $this->handle->handle($this->uid, $this->rid);
    }

    /**
     *   验证状态值是否合法
     */
    private function checkStatus()
    {
        if (in_array($this->status, [2,3,4])) {
            return false;
        }

        return true;
    }

    /**
     * 验证用户id是否正确
     */
    private function checkUid()
    {
        $user = User::find($this->uid);

        if (!$user) {
            return true;
        }
        return false;
    }

    /**
     * 验证法币交易单id是否正确
     */
    private function checkRid()
    {
        $order = Recharge::find($this->rid);

        if (!$order) {
            return true;
        }

        return false;
    }

    /**
     * 分配订单处理流程
     */
    private function setHandle(HandleInterface $handle)
    {
        $this->handle = $handle;
    }
}

